﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SortGUI
{
    public class OddEvenSort : SortBase//奇偶排序
    {
        override public void Sort(int[] array)
        {
            // 初始化
            Initialize();

            bool sorted = false;
            while (!sorted)
            {
                sorted = true;
                // 奇数位进行排序
                for (int i = 1; i < array.Length - 1; i += 2)
                {
                    lastSwappedIndices[0] = i - 1;
                    lastSwappedIndices[1] = i;
                    if (array[i] > array[i + 1])
                    {
                        Swap(ref array[i], ref array[i + 1]);
                        sorted = false;
                    }
                    count++;
                    SortNextStep();
                }

                // 偶数位进行排序
                for (int i = 0; i < array.Length - 1; i += 2)
                {
                    lastSwappedIndices[0] = i;
                    lastSwappedIndices[1] = i + 1;
                    if (array[i] > array[i + 1])
                    {
                        Swap(ref array[i], ref array[i + 1]);
                        sorted = false;
                    }
                    count++;
                    SortNextStep();
                }
            }

            // 排序完成
            Complete();
        }

        public override void Initialize()
        {
            count = 0;
            updataColor(isInitialize = false);
        }

        public override void SortNextStep()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex = 10000, swapped); // 更新UI
        }

        public override void Complete()
        {
            updateUiCallback(count, lastSwappedIndices, lastSortedIndex - 10000, swapped);
        }
    }
}
